package com.xtianzhuang.www.service.impl;

import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.xtianzhuang.www.dao.TdFileMapper;
import com.xtianzhuang.www.entity.TdFile;
import com.xtianzhuang.www.service.StudyService;
import com.xtianzhuang.www.service.base.BaseServiceBiz;


@Service("studyServiceBiz")
@Transactional(rollbackFor = Exception.class)
public class StudyServiceBiz extends BaseServiceBiz implements StudyService {

	@Autowired
	TdFileMapper tdFileMapper;

	@Override
	public void saveStudyNotes(String fileId, String fileName, long size, String suffix) {
		// TODO Auto-generated method stub
		TdFile tdFile = new TdFile();
		tdFile.setFileId(fileId);
		tdFile.setFileName(fileName);
		tdFile.setCreateStaffId(subject.getPrincipal().getUserName());
		tdFile.setCreateTime(new Date());
		tdFile.setFileSuffix(suffix);
		tdFile.setFileSize(size);
		tdFile.setFileType("01");
		tdFileMapper.insert(tdFile);
	}

	@Override
	public void checkFile(MultipartFile file) throws Exception {
		// TODO Auto-generated method stub
		// 判断上传的文件是否为空
		boolean isEmpty = file.isEmpty();
		logger.info("\t isEmpty=" + isEmpty);
		if (isEmpty) {
			throw new Exception("上传失败！上传的文件为空！");
		}

		// 检查文件大小
		long fileSize = file.getSize();
		logger.info("\t size=" + fileSize);
		if (fileSize > 5 * 1024 * 1024) {
			throw new Exception("上传失败！上传的文件大小超出了限制！");
		}

		// 检查文件MIME类型
		String contentType = file.getContentType();
		logger.info("\t contentType=" + contentType);
	}

	@Override
	public void checkDir(String parentDir) throws Exception {
		// TODO Auto-generated method stub
		File parent = new File(parentDir);
		if (!parent.exists()) {
			parent.mkdirs();
		}
		File parent2 = new File(parentDir + "/study");
		if (!parent2.exists()) {
			parent2.mkdirs();
		}
		File parent3 = new File(parentDir + "/study/" + subject.getPrincipal().getUserId());
		if (!parent3.exists()) {
			parent3.mkdirs();
		}
	}


}